package com.webvihar.access2db.activities;

import java.util.Arrays;
import java.util.List;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;

import com.webvihar.access2db.R;
import com.webvihar.access2db.dbutils.DataType;
import com.webvihar.access2db.dbutils.MySqlDataTypes;
import com.webvihar.access2db.model.TableField;
import com.webvihar.common.utils.Validation;

public class AddEditDeleteTableFieldActivity extends BaseActivity  implements OnClickListener, OnFocusChangeListener, OnItemSelectedListener, TextWatcher{

	private TextView titleTxt;
	private ImageButton titleActionButton;
	private EditText fieldNameTxt;
	private EditText lengthTxt;
	private EditText defaultTxt;
	private EditText commentTxt;
	private CheckBox zerofillCb;
	private CheckBox unsignedCb;
	private CheckBox allownullCb;
	private AutoCompleteTextView typeAc;
	private Spinner collationSp;
	private Button addFieldBtn;
	private Button editFieldBtn;
	private Button deleteFieldBtn;
	private ArrayAdapter<DataType> dataTypesAdapter;
	private MySqlDataTypes mysqlDataTypes;
	private int tableFieldIndex;
	private TableField tableField;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
		setContentView(R.layout.add_edit_delete_table_field);
		loadDataFromBundle();
		setTitleBar();
		initUI();
		setAdapters();
		setListener();
		loadTableDetails();
	}

	private void loadDataFromBundle() {
		Bundle bundle = getIntent().getExtras();
		tableFieldIndex = Integer.parseInt(bundle.getString(KEY_TABLE_FIELD_INDEX));
		if(tableFieldIndex >= 0) {
			tableField = AddEditDeleteTableActivity.tableFields.get(tableFieldIndex);
		}
	}
	
	private void loadTableDetails() {
		if(tableField != null) {
			TableField field = (TableField) tableField;
			fieldNameTxt.setText(field.fieldName != null ? field.fieldName : null);
			lengthTxt.setText(field.length != null ? field.length : null);
			defaultTxt.setText(field.defaultValue != null ? field.defaultValue : null);
			commentTxt.setText(field.comment != null ? field.comment : null);
			zerofillCb.setChecked(field.zerofill ? true : false);
			unsignedCb.setChecked(field.unsigned ? true : false);
			allownullCb.setChecked(field.allownull ? true : false);
			typeAc.setText(field.type != null ? field.type : null);
			//			collationSp.setSelection()
			// hide add button
			addFieldBtn.setVisibility(View.GONE);
			// display edit and delete buttons
			editFieldBtn.setVisibility(View.VISIBLE);
			deleteFieldBtn.setVisibility(View.VISIBLE);
		} else {
			// display add button
			addFieldBtn.setVisibility(View.VISIBLE);
			// hide edit and delete buttons
			editFieldBtn.setVisibility(View.GONE);
			deleteFieldBtn.setVisibility(View.GONE);
		}
	}

	public void setTitleBar() {
		titleTxt = (TextView) findViewById(R.id.title_txt);
		titleTxt.setText(getString(R.string.add_field_txt));
		titleActionButton = (ImageButton) findViewById(R.id.title_action_image_btn);
		titleActionButton.setVisibility(View.GONE);
	}

	private void initUI() {
		fieldNameTxt = (EditText)findViewById(R.id.add_table_field_field_et);
		lengthTxt = (EditText)findViewById(R.id.add_table_field_length_et);
		defaultTxt = (EditText)findViewById(R.id.add_table_field_default_et);
		commentTxt = (EditText)findViewById(R.id.add_table_field_comment_et);
		zerofillCb = (CheckBox)findViewById(R.id.add_table_field_zerofill_cb);
		unsignedCb = (CheckBox)findViewById(R.id.add_table_field_unsigned_cb);
		allownullCb = (CheckBox)findViewById(R.id.add_table_field_allownull_cb);
		typeAc = (AutoCompleteTextView) findViewById(R.id.add_table_field_data_type_auto_complete_textview);
		collationSp = (Spinner)findViewById(R.id.add_table_field_collation_sp);
		addFieldBtn = (Button)findViewById(R.id.add_edit_delete_table_field_add_field_btn);
		editFieldBtn = (Button)findViewById(R.id.add_edit_delete_table_field_edit_field_btn);
		deleteFieldBtn = (Button)findViewById(R.id.add_edit_delete_table_field_delete_field_btn);
	}

	private void setListener() {
		addFieldBtn.setOnClickListener(this);
		editFieldBtn.setOnClickListener(this);
		deleteFieldBtn.setOnClickListener(this);
		typeAc.setOnFocusChangeListener(this);
		typeAc.setOnItemSelectedListener(this);
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	private void setAdapters() {
		if(mysqlDataTypes == null) {
			mysqlDataTypes = new MySqlDataTypes();
		}
		dataTypesAdapter = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_dropdown_item_1line, mysqlDataTypes.datatypes);
		typeAc.setAdapter(dataTypesAdapter);
		typeAc.addTextChangedListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.add_edit_delete_table_field_add_field_btn:
			processData();
			break;
		case R.id.add_edit_delete_table_field_edit_field_btn:
			processEditField();
			break;
		case R.id.add_edit_delete_table_field_delete_field_btn:
			AddEditDeleteTableActivity.tableFields.remove(tableFieldIndex);
			showToast(getString(R.string.toast_field_deleted));
			AddEditDeleteTableFieldActivity.this.finish();
			break;
		default:
			break;
		}
	}
	
	private void processEditField() {
		tableField.fieldName = fieldNameTxt.getText().toString();
		tableField.type = typeAc.getText().toString();
		tableField.length = lengthTxt.getText().toString();
		tableField.zerofill = zerofillCb.isChecked();
		tableField.unsigned = unsignedCb.isChecked();
		tableField.allownull = allownullCb.isChecked();
		tableField.defaultValue = defaultTxt.getText().toString();
		tableField.collation = collationSp.getSelectedItem().toString();
		tableField.comment = commentTxt.getText().toString();
		showToast(getString(R.string.toast_field_updated));
		AddEditDeleteTableFieldActivity.this.finish();
	}
	
	private void processData() {
		String field = fieldNameTxt.getText().toString();
		String type = typeAc.getText().toString();
		String length = lengthTxt.getText().toString();
		String defaut = defaultTxt.getText().toString();
		String collation = collationSp.getSelectedItem().toString();
		String comment = commentTxt.getText().toString();
		if(isDataValid(field,type,length,defaut,collation,comment)) {
			AddEditDeleteTableActivity.tableFields.add(new TableField(fieldNameTxt.getText().toString(), 
					typeAc.getText().toString(), 
					lengthTxt.getText().toString(),
					zerofillCb.isChecked(),
					unsignedCb.isChecked(),
					allownullCb.isChecked(),
					defaultTxt.getText().toString(),
					collationSp.getSelectedItem().toString(),
					commentTxt.getText().toString()));
			this.finish();
		} 
	}

	private boolean isDataValid(String field, String type, String length,
			String defaut, String collation, String comment) {
		if(!Validation.isString(field)) {
			showToast(getResources().getString(R.string.prompt_field_name_txt));
			return false;
		}
		if(!Validation.isString(type)) {
			showToast(getResources().getString(R.string.prompt_type_txt));
			return false;
		}
		if(!Validation.isString(length)) {
			showToast(getResources().getString(R.string.prompt_length_txt));
			return false;
		}
		if(!Validation.isDefault(defaut)) {
			showToast(getResources().getString(R.string.prompt_default_txt));
			return false;
		}
		if(!Validation.isCollation(collation)) {
			showToast(getResources().getString(R.string.prompt_collation_txt));
			return false;
		}
		if(!Validation.isComment(comment)) {
			showToast(getResources().getString(R.string.prompt_comment_txt));
			return false;
		}
		return true;
	}

	@Override
	public void onFocusChange(View v, boolean hasFocus) {
		if(v == typeAc && hasFocus) {
			typeAc.showDropDown();
		}
	}

	@Override
	public void onItemSelected(AdapterView<?> adapter, View view, int position, long arg3) {
		DataType dataType = (DataType)adapter.getItemAtPosition(position);
		validateUi(dataType);
	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
	}

	private void validateUi(DataType dataType) {
		if(dataType != null) {
			lengthTxt.setEnabled((dataType.hasLength) ? true : false);
			zerofillCb.setEnabled((dataType.hasZeroFill) ? true : false);
			unsignedCb.setEnabled((dataType.hasUnsigned) ? true : false);
			allownullCb.setEnabled((dataType.hasAllowNull) ? true : false);
			defaultTxt.setEnabled((dataType.hasDefault) ? true : false);
			collationSp.setEnabled((dataType.hasCollation) ? true : false);
			commentTxt.setEnabled((dataType.hasComment) ? true : false);
		}
	}
	
	@Override
	public void afterTextChanged(Editable s) {		
		List<String> dataTypeNames = Arrays.asList(mysqlDataTypes.dataTypes);
		int position = dataTypeNames.indexOf(typeAc.getText().toString().toUpperCase());
		if(position >= 0 && position < mysqlDataTypes.datatypes.size()) { 
			DataType dataType = mysqlDataTypes.datatypes.get(position);
			validateUi(dataType);
		}
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count, int after) {
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
	}
}
